package com.xxl.vueadmin.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xxl.vueadmin.config.Expection.CaptachException;
import com.xxl.vueadmin.utils.Const;
import com.xxl.vueadmin.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0
 * @Author: 许啸林 验证码过滤器
 * @Date: 2021/7/29 16:49
 */
@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    private final String loginUrl = "/login";
    @Autowired
    RedisUtils redisUtil;
    @Autowired
    LoginFailureHandler loginFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String URI = httpServletRequest.getRequestURI();
        if(loginUrl.equals(URI) && "POST".equals(httpServletRequest.getMethod())) {
            try {
                validateCaptcha(httpServletRequest);
            } catch (CaptachException e) {
                log.info(e.getMessage());
                loginFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    public void validateCaptcha(HttpServletRequest request)  {
        String captachCode = request.getParameter("captcha");
        String captchaToken = request.getParameter("capToken");
        if(StringUtils.isBlank(captachCode) || StringUtils.isBlank(captchaToken)) {
            throw new CaptachException("验证码不能为空");
        }
        if(!captachCode.equals(redisUtil.hget(Const.CAPTCHA_KEY, captchaToken) )) {
            throw new CaptachException("验证码错误");
        }
        // 一次性使用
       // redisUtil.hdel(Const.CAPTCHA_KEY, captchaToken);
    }
}
